﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace Dependency_Injection
{
    class Program
    {
        static async Task Main()  ///Task?
        {
            var p = new Program();
            //初始化EF服务容器
            p.InitializeServices();
            //添加日志到控制台
            p.ConfigureLogging();
            //通过依赖注入容器获得BooksService实例
            var service = p.Container.GetService<UsersService>();
            await service.CreateTheDatabaseAsync();
            //添加书本到数据库
            await service.AddBooksAsync();
            //读取数据库中的数据
            await service.ReadBooksAsync();
            //释放容器资源
            p.Container.Dispose();
        }

       
        /// <summary>
        /// 初始化依赖注入框架容器
        /// </summary>
        private void InitializeServices()
        {
            //连接字符串
            //@"server=119.3.217.17,1433;database=Users;uid =rdsuser; password =12345678ccCC"; 
            const string ConnectionString =
            //@"server=(localdb)\mssqllocaldb;database=Users;trusted_connection=true";
            @"server=119.3.217.17,1433; user =rdsuser; password =12345678ccCC; database =Users;";
            //创建ServiceCollection实例
            var services = new ServiceCollection();
            //注册瞬时实例BooksService
            services.AddTransient<UsersService>()
              .AddEntityFrameworkSqlServer()//注册EF和SQLSERVER
              .AddDbContext<UserContxt>(options =>
                options.UseSqlServer(ConnectionString));//添加连接字符串
            services.AddLogging();//添加日志
            //创建服务容器
            Container = services.BuildServiceProvider();
        }
        public ServiceProvider Container { get; private set; }

        private void ConfigureLogging()
        {
            ILoggerFactory loggerFactory = Container.GetService<ILoggerFactory>();
            //日志消息送入控制台
            loggerFactory.AddConsole(LogLevel.Information);
        } 
    }
}

